// import {getOpenid, decodeMsg} from "@/api/authorize";

/**
 * 1.uni.login -> 获取code
 * 2.code -> openid -> 获取用户openid
 * 3.uni.getUserInfo -> 获取用户信息
 * 4.decodeMsg -> 解码获取用户完整信息
 * 5.保存用户信息
 */

// 1.uni.login -> 获取code
const wxLogin = () => {
  return new Promise(resolve => {
    uni.login({
      provider: 'weixin', success: (res) => {
        resolve(res)
      }
    })
  })
}

// 2.code -> openid -> 获取用户openid
const getOpenidApi = (code) => {
  return new Promise(resolve => {
    getOpenid({code: code}).then(res => {
      if (res.code == 1) {
        resolve(res.result);
      }
    })
  })
}

// 4.decodeMsg -> 解码获取用户完整信息
const decodeMsgApi = (encryptedData, iv, openid) => {
  return new Promise((resolve) => {
    decodeMsg({openid: openid, encryptedData: encryptedData, iv: iv}).then(res => {
      if (res.code == 1) {
        resolve(res.result);
      }
    })
  })
};

const getUserPhone = (encryptedData, iv) => {
  return new Promise(async resolve => {
    // 1.uni.login => 获取code
    const {code} = await wxLogin();
    // 2.code -> openid -> 获取用户openid
    const {openid} = await getOpenidApi(code);
    // 4.decode -> 解码获取用户完整信息
    const user = await decodeMsgApi(encryptedData, iv, openid);
    
    uni.$u.vuex('vuex_phone', user);
    uni.$u.toast('授权成功');
    
    resolve();
  })
}

export default getUserPhone;
